<template>
  <div class="sub-categroy">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread></SubBread>

      <!-- 筛选区 -->
      <SubFilter @filterchange="filterChange"></SubFilter>

      <!-- 商品区 -->
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="sortChange" />
        <!-- 列表 -->
        <ul>
          <li v-for="goods in goodsList" :key="goods.id">
            <GoodsItem :goods="goods" />
          </li>
        </ul>

        <XtxInfiniteLoading
          @infinite="getData"
          :loading="loading"
          :finished="finished"
        ></XtxInfiniteLoading>
      </div>
    </div>
  </div>
</template>
<script>
</script>
<script setup>
import SubSort from './components/sub-sort'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import GoodsItem from './components/goods-item'
import { findSubCategoryGoods } from '@/api/category'

import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory'
}
const route = useRoute()
const isAllChecked = ref(true)
const loading = ref(false)
const finished = ref(false)
// 获取商品
const goodsList = ref([])
// 请求参数
let reqParams = {
  page: 1,
  pazeSize: 20
}
// 当前分类id

const getData = () => {
  loading.value = true
  reqParams.cateGoryId = route.params.id
  findSubCategoryGoods(reqParams).then(({ result }) => {
    // 获取数据成功
    if (result.items.length) {
      // 追加数据
      goodsList.value.push(...result.items)
      reqParams.page++
    } else {
      // 无数据
      finished.value = true
    }
    // 清除
    loading.value = false
  })
}
// 切换分类
watch(
  () => route.params.id,
  (newVal) => {
    if (newVal && `/category/sub/${newVal}` == route.path) {
      // 清空
      finished.value = false
      goodsList.value = []
      reqParams = {
        page: 1,
        pageSize: 20
      }
    }
  }
)

const sortChange = (sortParams) => {
  finished.value = false
  // 合并参数
  reqParams = { ...reqParams, ...sortParams }
  reqParams.page = 1
  goodsList.value = []
}
// 更改筛选组件
const filterChange = (filterParams) => {
  finished.value = false
  // 合并参数
  reqParams = { ...reqParams, ...filterParams }
  reqParams.page = 1
  goodsList.value = []
}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
